//
//  SIComposeTypeView.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/9.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit
import pop

class SIComposeTypeView: UIView {
    ///按钮滚动视图
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var returnButton: UIButton!
    ///关闭按钮的中心x的约束
    @IBOutlet weak var closeButtonCons: NSLayoutConstraint!
    ///返回上一页按钮的中心x的约束
    @IBOutlet weak var returnButtonCons: NSLayoutConstraint!
    
    private var completionBlock:((clsName: String?) -> ())?
    
    ///按钮数组
    private let buttonsInfo = [["imageName": "tabbar_compose_idea", "title": "文字", "clsName": "SIComposeViewController"],
                               ["imageName": "tabbar_compose_photo", "title": "照片/视频"],
                               ["imageName": "tabbar_compose_weibo", "title": "长微博"],
                               ["imageName": "tabbar_compose_lbs", "title": "签到"],
                               ["imageName": "tabbar_compose_review", "title": "点评"],
                               ["imageName": "tabbar_compose_more", "title": "更多", "actionName": "clickMore"],
                               ["imageName": "tabbar_compose_friend", "title": "好友圈"],
                               ["imageName": "tabbar_compose_wbcamera", "title": "微博相机"],
                               ["imageName": "tabbar_compose_music", "title": "音乐"],
                               ["imageName": "tabbar_compose_shooting", "title": "拍摄"]
    ]


    class func composeTypeView() -> SIComposeTypeView {
        
        let nib = UINib(nibName: "SIComposeTypeView", bundle: nil)
        
        let v = nib.instantiate(withOwner: nil
            , options: nil)[0] as! SIComposeTypeView
        
        v.frame = UIScreen.main().bounds
        
        v.setupUI()
        
        return v
    }
    
    //MARK: -显示当前视图
    func show(completion: (clsName: String?) -> ()) {
        
        completionBlock = completion
        
        guard let vc = UIApplication.shared().keyWindow?.rootViewController else {
            
            return
        }
        //FIXME: - bug--
        vc.view.addSubview(self)
        
        showCurrentView()
        
        
    }
    
    //MARK: -按钮点击事件
    @objc private func clickButton(button: SIComposeTypeButton) {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated() {
            
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            
            let scale = (button == btn) ? 2 : 0.2
            
            scaleAnim.toValue = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.duration = 0.5
            
            btn.pop_add(scaleAnim, forKey: nil)
            
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            
            btn.pop_add(alphaAnim, forKey: nil)
            
            if i == 0 {
                
                alphaAnim.completionBlock = {(_, _) in
                    
                    print("完成回调展现控制器")
                    
                    self.completionBlock?(clsName: button.clsName)
                    
                }
            }
        }
    }
    
    @objc private func clickMore() {
        print("点击更多")
        
        let offset = CGPoint(x: scrollView.bounds.width, y: 0)
        scrollView.setContentOffset(offset, animated: true)
        
        returnButton.isHidden = false
        
        let margin = scrollView.bounds.width / 6
        
        closeButtonCons.constant += margin
        returnButtonCons.constant -= margin
        
        UIView.animate(withDuration: 0.25) { 
            self.layoutIfNeeded()
        }
    }
    
    //MARK: -关闭按钮
    @IBAction func CloseButton(_ sender: AnyObject) {
//        removeFromSuperview()
        hideButton()
    }
    //MARK: -返回上一页按钮
    @IBAction func returnButton(_ sender: AnyObject) {
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
        
        closeButtonCons.constant = 0
        returnButtonCons.constant = 0
        
        UIView.animate(withDuration: 0.25, animations: { 
            self.layoutIfNeeded()
            self.returnButton.alpha = 0
            }) { (_) in
                
                self.returnButton.isHidden = true
                self.returnButton.alpha = 1
        }
    }
    
}

private extension SIComposeTypeView {
    
    //MARK: -动画隐藏button
    private func hideButton() {
        
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        
        let v = scrollView.subviews[page]
        
        for (i, btn) in v.subviews.enumerated().reversed() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            
            btn.layer.pop_add(anim, forKey: nil)
            
            if i == 0 {
                
                anim.completionBlock = {(_, _) in
                    self.hideCurrentView()
                }
            }
            
        }
        
    }
    
    //MARK:动画完成,button消失隐藏当前视图
    private func hideCurrentView() {
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 1
        anim.toValue = 0
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        anim.completionBlock = {(_, _) -> () in
            
            self.removeFromSuperview()
        }
        
    }
    
    //MARK: -展示入场pop动画
    private func showCurrentView() {
        
        let anim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        
        anim.fromValue = 0
        anim.toValue = 1
        anim.duration = 0.25
        
        pop_add(anim, forKey: nil)
        
        showButtons()
    }
    
    //MARK: -展示buttons
    private func showButtons() {
        
        let v = scrollView.subviews[0]
        
        for (i, btn) in v.subviews.enumerated() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            
            anim.springBounciness = 8
            anim.springSpeed = 8
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            
            btn.pop_add(anim, forKey: nil)
        }
        
    }
}

private extension SIComposeTypeView {
    
    //MARK: 建立scrollView的视图
    func setupUI() {
        
        layoutIfNeeded()
        
        let rect = scrollView.bounds
        
        let width = scrollView.bounds.width
        
        for i in 0..<2 {
            
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
            
            addButtons(v: v, idx: i * 6)
            
            scrollView.addSubview(v)
            
        }
        
        scrollView.contentSize = CGSize(width: 2 * width, height: 0)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isScrollEnabled = false
        
    }
    //MARK: -添加两个view的button
    func addButtons(v: UIView, idx: Int) {
        
        let count = 6
        
        for i in idx..<(idx + count) {
            
            if i >= buttonsInfo.count {
                break
            }
            let dict = buttonsInfo[i]
            
            guard let imageName = dict["imageName"],
                title = dict["title"] else {
                    
                    continue
            }
            
            let btn = SIComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            v.addSubview(btn)
            
            if let actionName = dict["actionName"] {
                
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            } else {
                
                btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
            }
            
            btn.clsName = dict["clsName"]
        }
        
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4
        
        for (i, btn) in v.subviews.enumerated() {
            
            let y: CGFloat = (i > 2) ? (v.bounds.height - btnSize.height) : 0
            
            let col = i % 3
            
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            
            btn.frame = CGRect(x: x, y: y, width: btnSize.width, height: btnSize.height)
            
        }
    }
}
